package com.heima.juc.n8;

import com.heima.juc.n2.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author : leimingchao
 * @date Date : 2022年02月19日 17:29
 */
@Slf4j(topic = "c.TestSubmit")
public class TestSubmit {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService threadPool = Executors.newFixedThreadPool(2);

        //method1(threadPool);

        //method2(threadPool);

        String result = threadPool.invokeAny(Arrays.asList(
                () -> {
                    log.debug("begin....1");
                    Thread.sleep(1000);
                    log.debug("end....1");
                    return "1";
                },
                () -> {
                    log.debug("begin....2");
                    Thread.sleep(500);
                    log.debug("end....2");
                    return "2";
                },
                () -> {
                    log.debug("begin....3");
                    Thread.sleep(2000);
                    log.debug("end....3");
                    return "3";
                }
                )

        );

        log.debug("{}", result);
    }

    private static void method2(ExecutorService threadPool) throws InterruptedException {
        List<Future<String>> futures = threadPool.invokeAll(Arrays.asList(
                    () -> {
                        log.debug("begin....");
                        Sleeper.sleep(1);
                        return "1";
                    },
                    () -> {
                        log.debug("begin....");
                        Sleeper.sleep(0.5);
                        return "2";
                    },
                    () -> {
                        log.debug("begin....");
                        Sleeper.sleep(2);
                        return "3";
                    }
                )

        );

        futures.forEach(f -> {
            try {
                log.debug("{}", f.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });
    }

    private static void method1(ExecutorService threadPool) throws InterruptedException, ExecutionException {
        Future<String> future = threadPool.submit(() -> {
            log.debug("running....");
            Sleeper.sleep(1);
            return "ok";
        });

        log.debug("{}", future.get());
    }
}
